package cn.javaxc.mvcwork.modules.notifier;
import cn.javaxc.mvcwork.controller.MVCConstant;
import cn.javaxc.mvcwork.framework.beans.TFormBean;
import cn.javaxc.mvcwork.modules.admin.Contact;
import cn.javaxc.mvcwork.util.common.*;
import java.sql.*;
import java.text.DateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import cn.javaxc.mvcwork.controller.AppUtils;
import cn.javaxc.model.base.*;
import cn.javaxc.mvcwork.util.helper.FrameHelper;


//2015-01-25_19-42-43 删除方法active,cacel,insertRecipients,parseUserGroups
public class Campaign extends TFormBean {

  public final static int IDLE = 1;
  public final static int QUEUE = 2;
  public final static int STARTED = 3;
  public final static int FINISHED = 4;
  public final static int ERROR = 5;
  public final static int CANCELED = 6;

  public final static String IDLE_TEXT = "Idle";
  public final static String QUEUE_TEXT = "In Queue";
  public final static String STARTED_TEXT = "Sending Messages";
  public final static String FINISHED_TEXT = "Messages Sent";
  public final static String ERROR_TEXT = "Error in Campaign";
  public final static String CANCELED_TEXT = "Canceled";

  //campaign types
  public final static int GENERAL = 1;
  public final static int INSTANT = 2;

  private int id = -1;
  private String name = null;
  private String description = null;
  private int messageId = -1;
  private int groupId = -1;
  private int runId = -1;
  private int statusId = -1;
  private int owner = -1;
  private int modifiedBy = -1;
  private int enteredBy = -1;
  private java.sql.Timestamp activeDate = null;
  private java.sql.Timestamp inactiveDate = null;
  private java.sql.Timestamp entered = null;
  private java.sql.Timestamp modified = null;
  private boolean enabled = true;
  private String status = null;
  private boolean active = false;
  private String replyTo = null;
  private String subject = null;
  private String message = null;
  private int sendMethodId = -1;
  private int type = GENERAL;
  private String activeDateTimeZone = null;
  private java.sql.Timestamp trashedDate = null;
  private boolean partComplete = false;

  private boolean buildGroupMaps = false;
  private int files = 0;
  private String deliveryName = null;
  private int deliveryType = -1;
  private int recipientCount = -1;
  private int responseCount = -1;
  private int sentCount = -1;
  private String messageName = "";
  private int surveyId = -1;
  private String serverName = "";
  private String groupList = "";
  private int groupCount = -1;
  private int approvedBy = -1;
  private java.sql.Timestamp approvalDate = null;
  private LinkedHashMap groups = null;
  private MessageAttachmentList messageAttachments = new MessageAttachmentList();
  private java.sql.Timestamp lastResponse = null;
  private String messageSubject = null;
  private boolean hasAddressRequest = false;
  private int addressSurveyId = -1;
  private int addressResponseCount = -1;
  private java.sql.Timestamp lastAddressResponse = null;
  private boolean hasSurvey = false;
  protected String bcc = null;
  protected String cc = null;


  
  public Campaign() {
  }


  
  public Campaign(ResultSet rs) throws SQLException {
    buildRecord(rs);
  }


  
  public void setActiveDateTimeZone(String tmp) {
    this.activeDateTimeZone = tmp;
  }


  
  public String getActiveDateTimeZone() {
    return activeDateTimeZone;
  }


  
  public void setTrashedDate(java.sql.Timestamp tmp) {
    this.trashedDate = tmp;
  }


  
  public void setTrashedDate(String tmp) {
    this.trashedDate = DatabaseUtils.parseTimestamp(tmp);
  }


  
  public java.sql.Timestamp getTrashedDate() {
    return trashedDate;
  }


  
  public int getSurveyId() {
    return surveyId;
  }


  
  public int getActiveSurveyId() {
    if (active) {
      return surveyId;
    } else {
      return -1;
    }
  }


  
  public void setSurveyId(int surveyId) {
    this.surveyId = surveyId;
  }


  
  public void setSurveyId(String surveyId) {
    this.surveyId = Integer.parseInt(surveyId);
  }


  
  public void setGroups(LinkedHashMap groups) {
    this.groups = groups;
  }


  
  public void setResponseCount(int responseCount) {
    this.responseCount = responseCount;
  }


  
  public void setLastResponse(java.sql.Timestamp lastResponse) {
    this.lastResponse = lastResponse;
  }


  
  public void setType(int type) {
    this.type = type;
  }


  
  public void setType(String type) {
    this.type = Integer.parseInt(type);
  }


  
  public void setMessageSubject(String tmp) {
    this.messageSubject = tmp;
  }


  
  public void setHasAddressRequest(boolean tmp) {
    this.hasAddressRequest = tmp;
  }


  
  public void setHasAddressRequest(String tmp) {
    this.hasAddressRequest = DatabaseUtils.parseBoolean(tmp);
  }


  
  public void setAddressSurveyId(int tmp) {
    this.addressSurveyId = tmp;
  }


  
  public void setAddressSurveyId(String tmp) {
    this.addressSurveyId = Integer.parseInt(tmp);
  }

  
  public void setAddressResponseCount(int tmp) {
    this.addressResponseCount = tmp;
  }


  
  public void setAddressResponseCount(String tmp) {
    this.addressResponseCount = Integer.parseInt(tmp);
  }


  
  public void setLastAddressResponse(java.sql.Timestamp tmp) {
    this.lastAddressResponse = tmp;
  }


  
  public void setLastAddressResponse(String tmp) {
    this.lastAddressResponse = DatabaseUtils.parseTimestamp(tmp);
  }


  
  public void setHasSurvey(boolean tmp) {
    this.hasSurvey = tmp;
  }


  
  public void setHasSurvey(String tmp) {
    this.hasSurvey = DatabaseUtils.parseBoolean(tmp);
  }


  
  public String getMessageSubject() {
    return messageSubject;
  }


  
  public boolean getHasAddressRequest() {
    return hasAddressRequest;
  }

  
  public int getAddressSurveyId() {
    return addressSurveyId;
  }


  
  public int getAddressResponseCount() {
    return addressResponseCount;
  }


  
  public java.sql.Timestamp getLastAddressResponse() {
    return lastAddressResponse;
  }


  
  public boolean getHasSurvey() {
    return hasSurvey;
  }


  
  public int getType() {
    return type;
  }


  
  public java.sql.Timestamp getLastResponse() {
    return lastResponse;
  }


  
  public String getLastResponseString() {
    String tmp = "";
    try {
      return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(
          lastResponse);
    } catch (NullPointerException e) {
    }
    return tmp;
  }


  
  public String getLastAddressResponseString() {
    String tmp = "";
    try {
      return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(
          lastAddressResponse);
    } catch (NullPointerException e) {
    }
    return tmp;
  }


  
  public int getResponseCount() {
    return responseCount;
  }


  
  public LinkedHashMap getGroups() {
    return groups;
  }


  
  public String getBcc() {
    return bcc;
  }


  
  public void setBcc(String tmp) {
    this.bcc = tmp;
  }


  
  public String getCc() {
    return cc;
  }


  
  public void setCc(String tmp) {
    this.cc = tmp;
  }


  public MessageAttachmentList getMessageAttachments() {
		return messageAttachments;
	}


	public void setMessageAttachments(MessageAttachmentList messageAttachments) {
		this.messageAttachments = messageAttachments;
	}
  
  public Campaign(Connection db, String campaignId) throws SQLException {
    queryRecord(db, Integer.parseInt(campaignId));
  }


  
  public Campaign(Connection db, int campaignId) throws SQLException {
    queryRecord(db, campaignId);
  }


  
  public void queryRecord(Connection db, int campaignId) throws SQLException {
    if (campaignId <= 0) {
      throw new SQLException("Invalid ID specified.");
    }
    PreparedStatement pst = null;
    ResultSet rs = null;

    String sql =
        "SELECT c.*, msg.name AS messageName, msg.subject AS messageSubject, dt.code AS deliveryType, dt.description AS deliveryTypeName " +
            "FROM campaign c " +
            "LEFT JOIN " + DatabaseUtils.addQuotes(db, "message") + " msg ON (c.message_id = msg.id) " +
            "LEFT JOIN lookup_delivery_options dt ON (c.send_method_id = dt.code) " +
            "WHERE c.campaign_id = ? ";
    pst = db.prepareStatement(sql);
    pst.setInt(1, campaignId);
    rs = pst.executeQuery();
    if (rs.next()) {
      buildRecord(rs);
    }
    rs.close();
    pst.close();
    if (id == -1) {
      throw new SQLException(MVCConstant.NOT_FOUND_ERROR);
    }
  }


  
  public void buildUserGroupMaps(Connection db) throws SQLException {
    
  }



  
  public void setRecipientCount(int recipientCount) {
    this.recipientCount = recipientCount;
  }


  
  public void setRecipientCount(String recipientCount) {
    this.recipientCount = Integer.parseInt(recipientCount);
  }


  
  public void setSentCount(int tmp) {
    this.sentCount = tmp;
  }


  
  public void setMessageName(String messageName) {
    this.messageName = messageName;
  }


  
  public String getServerName() {
    return serverName;
  }


  
  public void setServerName(String serverName) {
    this.serverName = serverName;
  }


  
  public void setGroupList(String groupList) {
    this.groupList = groupList;
  }


  
  public int getApprovedBy() {
    return approvedBy;
  }


  
  public void setApprovedBy(int approvedBy) {
    this.approvedBy = approvedBy;
  }

  
  public void setApprovedBy(String approvedBy) {
    this.approvedBy = Integer.parseInt(approvedBy);
  }

  
  public java.sql.Timestamp getApprovalDate() {
    return approvalDate;
  }

  
  public void setApprovalDate(java.sql.Timestamp approvalDate) {
    this.approvalDate = approvalDate;
  }

  
  public void setApprovalDate(String approvalDate) {
    this.approvalDate = DatabaseUtils.parseTimestamp(approvalDate);
  }

  
  public void setId(int tmp) {
    this.id = tmp;
  }


  
  public void setId(String tmp) {
    this.setId(Integer.parseInt(tmp));
  }


  
  public void setActive(boolean active) {
    this.active = active;
  }


  
  public void setActive(String tmp) {
    active = DatabaseUtils.parseBoolean(tmp);
    ;
  }


  
  public void setReplyTo(String tmp) {
    this.replyTo = tmp;
  }


  
  public void setSubject(String tmp) {
    this.subject = tmp;
  }


  
  public void setMessage(String tmp) {
    this.message = tmp;
  }


  
  public void setSendMethodId(int tmp) {
    this.sendMethodId = tmp;
  }


  
  public void setSendMethodId(String tmp) {
    this.sendMethodId = Integer.parseInt(tmp);
  }


  
  public void setName(String tmp) {
    this.name = tmp;
  }


  
  public void setDescription(String tmp) {
    this.description = tmp;
  }


  
  public void setStatus(String status) {
    this.status = status;
  }


  
  public void setMessageId(int tmp) {
    this.messageId = tmp;
  }


  
  public void setMessageId(String tmp) {
    this.messageId = Integer.parseInt(tmp);
  }


  
  public void setGroupId(int tmp) {
    this.groupId = tmp;
  }


  
  public void setGroupId(String tmp) {
    this.groupId = Integer.parseInt(tmp);
  }


  
  public void setRunId(int tmp) {
    this.runId = tmp;
  }


  
  public void setRunId(String tmp) {
    this.runId = Integer.parseInt(tmp);
  }


  
  public void setStatusId(int tmp) {
    this.statusId = tmp;

    switch (statusId) {
      case IDLE:
        status = IDLE_TEXT;
        break;
      case QUEUE:
        status = QUEUE_TEXT;
        break;
      case STARTED:
        status = STARTED_TEXT;
        break;
      case ERROR:
        status = "Unspecified error";
        break;
      case FINISHED:
        status = FINISHED_TEXT;
        break;
      default:
        break;
    }
  }


  
  public void setStatusId(String tmp) {
    this.setStatusId(Integer.parseInt(tmp));
  }


  
  public void setOwner(int tmp) {
    this.owner = tmp;
  }


  
  public void setOwner(String tmp) {
    this.owner = Integer.parseInt(tmp);
  }


  
  public void setActiveDate(java.sql.Timestamp tmp) {
    this.activeDate = tmp;
  }


  
  public void setActiveDate(String tmp) {
    this.activeDate = DatabaseUtils.parseDateToTimestamp(tmp);
  }

  
  public java.sql.Timestamp getInactiveDate() {
    return inactiveDate;
  }

  
  public void setInactiveDate(java.sql.Timestamp tmp) {
    this.inactiveDate = tmp;
  }


  
  public void setInactiveDate(String tmp) {
    this.inactiveDate = DatabaseUtils.parseDateToTimestamp(tmp);
  }


  
  public void setEntered(Timestamp tmp) {
    this.entered = tmp;
  }


  
  public void setEntered(String tmp) {
    this.entered = DateUtils.parseTimestampString(tmp);
  }


  
  public void setModified(String tmp) {
    this.modified = DateUtils.parseTimestampString(tmp);
  }


  
  public void setEnteredBy(int tmp) {
    this.enteredBy = tmp;
  }


  
  public void setEnteredBy(String tmp) {
    this.enteredBy = Integer.parseInt(tmp);
  }


  
  public void setModified(Timestamp tmp) {
    this.modified = tmp;
  }


  
  public void setModifiedBy(int tmp) {
    this.modifiedBy = tmp;
  }


  
  public void setModifiedBy(String tmp) {
    this.modifiedBy = Integer.parseInt(tmp);
  }


  
  public void setEnabled(boolean tmp) {
    enabled = tmp;
  }


  
  public void setEnabled(String tmp) {
    enabled = DatabaseUtils.parseBoolean(tmp);
  }


  
  public void setDeliveryName(String deliveryName) {
    this.deliveryName = deliveryName;
  }


  
  public void setDeliveryType(int tmp) {
    this.deliveryType = tmp;
  }


  
  public void setDeliveryType(String tmp) {
    this.deliveryType = Integer.parseInt(tmp);
  }


  
  public void setGroups(HttpServletRequest request) {
    StringBuffer sb = new StringBuffer();
    int selectCount = 0;
    String item = null;
    while ((item = request.getParameter("select" + (++selectCount))) != null) {
      if (DatabaseUtils.parseBoolean(
          request.getParameter("select" + selectCount + "check"))) {
        if (sb.length() > 0) {
          sb.append("*");
        }
        sb.append(item);
      }
    }
    groupList = sb.toString();
  }



  
  public java.sql.Timestamp getModified() {
    return modified;
  }


  
  public int getSendMethodId() {
    return sendMethodId;
  }


  
  public String getDeliveryName() {
    return deliveryName;
  }


  
  public int getDeliveryType() {
    return deliveryType;
  }


  
  public int getRecipientCount() {
    return recipientCount;
  }


  
  public int getSentCount() {
    return sentCount;
  }



  
  public String getMessageName() {
    return messageName;
  }


  
  public boolean getActive() {
    return active;
  }


  
  public String getActiveYesNo() {
    if (active == true) {
      return ("Yes");
    } else {
      return ("No");
    }
  }


  
  public String getActive(String tmp) {
    if (active == true) {
      return tmp;
    } else {
      return "";
    }
  }


  
  public java.sql.Timestamp getActiveDate() {
    return activeDate;
  }


  
  public String getActiveDateString() {
    String tmp = "";
    try {
      return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(activeDate);
    } catch (NullPointerException e) {
    }
    return tmp;
  }


  
  public String getStatus() {
    return status;
  }


  
  public String getGroupList() {
    return groupList;
  }


  
  public int getGroupCount() {
    return groupCount;
  }


  
  public int getId() {
    return id;
  }


  
  public String getName() {
    return name;
  }


  
  public String getDescription() {
    return description;
  }


  
  public int getMessageId() {
    return messageId;
  }


  
  public String getReplyTo() {
    return replyTo;
  }


  
  public String getMessage() {
    return message;
  }


  
  public String getSubject() {
    return subject;
  }


  
  public int getGroupId() {
    return groupId;
  }


  
  public int getRunId() {
    return runId;
  }


  
  public int getStatusId() {
    return statusId;
  }


  
  public int getOwner() {
    return owner;
  }


  
  public int getEnteredBy() {
    return enteredBy;
  }


  
  public int getModifiedBy() {
    return modifiedBy;
  }


  
  public String getModifiedString() {
    String tmp = "";
    try {
      return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(
          modified);
    } catch (NullPointerException e) {
    }
    return tmp;
  }


  
  public java.sql.Timestamp getEntered() {
    return entered;
  }


  
  public String getEnteredString() {
    String tmp = "";
    try {
      return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(
          entered);
    } catch (NullPointerException e) {
    }
    return tmp;
  }


  
  public boolean getEnabled() {
    return enabled;
  }


  
  public boolean getPartComplete() {
    return partComplete;
  }


  
  public void setPartComplete(boolean tmp) {
    this.partComplete = tmp;
  }


  
  public void setPartComplete(String tmp) {
    this.partComplete = DatabaseUtils.parseBoolean(tmp);
  }




  
  public boolean getBuildGroupMaps() {
    return buildGroupMaps;
  }


  
  public void setBuildGroupMaps(boolean tmp) {
    this.buildGroupMaps = tmp;
  }


  
  public void setBuildGroupMaps(String tmp) {
    this.buildGroupMaps = DatabaseUtils.parseBoolean(tmp);
  }


  
  public String getRange() {
    StringTokenizer strt = new StringTokenizer(this.getGroupList(), "*");
    String range = "";
    boolean b = true;

    while (strt.hasMoreTokens()) {
      String tmpString = (String) strt.nextToken();

      if (b == true) {
        range = range + tmpString;
        b = false;
      } else {
        range = range + ", " + tmpString;
      }
    }

    return range;
  }


  
  public String getMessageChecked(int tmp) {
    if (messageId == tmp) {
      return "checked";
    } else {
      return "";
    }
  }


  
  public String getGroupChecked(int tmp) {
    if (groupList != null || groupList.length() > 0) {
      StringTokenizer st = new StringTokenizer(groupList, "*");

      while (st.hasMoreTokens()) {
        String tmpString = (String) st.nextToken();
        if (tmpString.equals(String.valueOf(tmp))) {
          return "checked";
        }
      }
    }
    return "";
  }


  
  public boolean isReadyToActivate() {
    return (hasGroups() && hasMessage() && hasDetails());
  }


  
  public boolean hasGroups() {
    return (groupList != null && !groupList.equals(""));
  }


  
  public boolean hasMessage() {
    return (messageId > 0);
  }


  
  public boolean hasSurvey() {
    return (surveyId > 0);
  }


  
  public boolean hasDetails() {
    return (activeDate != null);
  }


  
  public boolean hasRun() {
    return (statusId == FINISHED);
  }


  
  public boolean hasFiles() {
    return (files > 0);
  }



  
  public void buildFileCount(Connection db) throws SQLException {
    //All internal documents for a campaign
    files = retrieveRecordCount(db, "documents", id);
  }

  public static int retrieveRecordCount(Connection db, Object linkModuleId, Object linkItemId) throws SQLException {
    int count = 0;
    SQLMap pst = FrameHelper.getBaseSQL().createStatement(
        "SELECT COUNT(*) as filecount " +
            "FROM ts_files pf " +
            "WHERE pf.link_module_id = ? and pf.link_item_id = ? ");
    pst.setString(1, linkModuleId+"");
    pst.setObject(2, linkItemId);
    SQLList<SQLMap> rs = pst.executeQuery(null,null);
    if (rs.size()>0) {
      count = rs.get(0).getInt("filecount");
    }
    return count;
  }


 

  
  public boolean insert(Connection db) throws SQLException {
    StringBuffer sql = new StringBuffer();
    boolean commit = true;
    try {
      commit = db.getAutoCommit();
      if (commit) {
        db.setAutoCommit(false);
      }
      sql.append(
          "INSERT INTO campaign " +
              "(enteredby, modifiedby, name, message_id, " +
              "reply_addr, subject, " + DatabaseUtils.addQuotes(db, "message") + ", send_method_id, " +
              "inactive_date, approval_date, " + DatabaseUtils.addQuotes(db, "type") + ", ");
      if (id > -1) {
        sql.append("campaign_id, ");
      }
      sql.append("entered, ");
      sql.append("approvedby ) ");
      sql.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ");
      if (id > -1) {
        sql.append("?, ");
      }
      if (entered != null) {
        sql.append("?, ");
      } else {
        sql.append(DatabaseUtils.getCurrentTimestamp(db) + ", ");
      }
      sql.append("?) ");
      int i = 0;
      PreparedStatement pst = db.prepareStatement(sql.toString());
      pst.setInt(++i, this.getEnteredBy());
      pst.setInt(++i, this.getModifiedBy());
      pst.setString(++i, this.getName());
      pst.setInt(++i, this.getMessageId());
      pst.setString(++i, replyTo);
      pst.setString(++i, subject);
      pst.setString(++i, message);
      pst.setInt(++i, sendMethodId);
      pst.setTimestamp(++i, inactiveDate);
      pst.setTimestamp(++i, approvalDate);
      pst.setInt(++i, type);
      if (id > -1) {
        pst.setInt(++i, id);
      }
      if (entered != null) {
        pst.setTimestamp(++i, entered);
      }
      DatabaseUtils.setInt(pst, ++i, this.getApprovedBy());
      pst.execute();
      pst.close();
      id = DatabaseUtils.getCurrVal(db, "campaign_campaign_id_seq", id);
      this.update(db, true);
      if (this.getGroupList() != null && !this.getGroupList().equals("")) {
        if (System.getProperty("DEBUG") != null) {
          System.out.println("Campaign-> GroupList: " + this.getGroupList());
        }
        StringBuffer groupSql = new StringBuffer();
        StringTokenizer strt = new StringTokenizer(this.getGroupList(), "*");
        PreparedStatement pstx = null;

        while (strt.hasMoreTokens()) {
          String tmpString = (String) strt.nextToken();
          groupSql.append(
              "INSERT INTO campaign_list_groups " +
                  "(campaign_id, group_id ) " +
                  "VALUES (?, ?) ");
          int j = 0;
          pstx = db.prepareStatement(groupSql.toString());
          pstx.setInt(++j, this.getId());
          pstx.setInt(++j, Integer.parseInt(tmpString));
          pstx.execute();
          pstx.close();
        }
      }
      if (commit) {
        db.commit();
      }
    } catch (SQLException e) {
      if (commit) {
        db.rollback();
      }
      throw new SQLException(e.getMessage());
    } finally {
      if (commit) {
        db.setAutoCommit(true);
      }
    }
    return true;
  }



  
  public boolean insertGroups(Connection db) throws SQLException {
    try {
      db.setAutoCommit(false);

      deleteAllGroups(db);

      if (this.getGroupList() != null && !this.getGroupList().equals("")) {
        StringTokenizer strt = new StringTokenizer(this.getGroupList(), "*");
        while (strt.hasMoreTokens()) {
          String tmpString = (String) strt.nextToken();

          PreparedStatement pstx = null;
          String groupSql =
              "INSERT INTO campaign_list_groups " +
                  "(campaign_id, group_id ) " +
                  "VALUES (?, ?) ";
          int j = 0;
          pstx = db.prepareStatement(groupSql);
          pstx.setInt(++j, this.getId());
          pstx.setInt(++j, Integer.parseInt(tmpString));
          pstx.execute();
          pstx.close();
        }
      }

      Statement st = db.createStatement();
      st.executeUpdate(
          "UPDATE campaign " +
          "SET modified = CURRENT_TIMESTAMP " +
              "WHERE campaign_id = " + id);
      //"WHERE id = " + id);
      st.close();

      db.commit();
    } catch (SQLException e) {
      db.rollback();
      throw new SQLException(e.getMessage());
    } finally {
      db.setAutoCommit(true);
    }
    return true;
  }


  
  public boolean deleteAllGroups(Connection db) throws SQLException {
    PreparedStatement pstx = null;
    String groupSql =
        "DELETE FROM campaign_list_groups " +
            "WHERE campaign_id = ? ";
    int j = 0;
    pstx = db.prepareStatement(groupSql);
    pstx.setInt(++j, this.getId());
    pstx.execute();
    pstx.close();
    return true;
  }


  
  public boolean deleteGroups(Connection db) throws SQLException {
    try {
      db.setAutoCommit(false);
      if (this.getGroupList() != null && !this.getGroupList().equals("")) {
        StringTokenizer strt = new StringTokenizer(this.getGroupList(), "*");
        while (strt.hasMoreTokens()) {
          String tmpString = (String) strt.nextToken();
          PreparedStatement pstx = null;
          StringBuffer groupSql = new StringBuffer();
          groupSql.append(
              "DELETE FROM campaign_list_groups " +
                  "WHERE campaign_id = ? " +
                  "AND group_id = ? ");
          int j = 0;
          pstx = db.prepareStatement(groupSql.toString());
          pstx.setInt(++j, this.getId());
          pstx.setInt(++j, Integer.parseInt(tmpString));
          pstx.execute();
          pstx.close();
        }

        Statement st = db.createStatement();
        st.executeUpdate(
            "UPDATE campaign " +
            "SET modified = CURRENT_TIMESTAMP " +
                "WHERE campaign_id = " + id);
        //"WHERE id = " + id);
        st.close();
      }
      db.commit();
    } catch (SQLException e) {
      db.rollback();
      throw new SQLException(e.getMessage());
    } finally {
      db.setAutoCommit(true);
    }
    return true;
  }


  
  public int update(Connection db) throws SQLException {
    int resultCount = -1;
	boolean commit = db.getAutoCommit();
    try {
      if (commit)db.setAutoCommit(false);
      resultCount = this.update(db, false);
      if (commit)db.commit();
    } catch (Exception e) {
      if (commit)db.rollback();
      throw new SQLException(e.getMessage());
    } finally {
      if (commit)db.setAutoCommit(true);
    }
    return resultCount;
  }





  
  public int insertRun(Connection db) throws SQLException {
    CampaignRun thisRun = new CampaignRun();
    thisRun.setCampaignId(this.getId());
    thisRun.setTotalContacts(this.getRecipientCount());
    thisRun.setTotalSent(this.getSentCount());
    thisRun.insert(db);
    return thisRun.getId();
  }


  
  public int updateDetails(Connection db) throws SQLException {
    if (this.getId() == -1) {
      throw new SQLException("Campaign ID was not specified");
    }
    int resultCount = 0;

    PreparedStatement pst = null;
    pst = db.prepareStatement(
        "UPDATE campaign " +
            "SET name = ?, " +
            "description = ?, " +
            "modifiedby = ?, " +
            "modified = CURRENT_TIMESTAMP " +
            "WHERE campaign_id = " + id);
    //"WHERE id = " + id);
    int i = 0;
    pst.setString(++i, name);
    pst.setString(++i, description);
    pst.setInt(++i, modifiedBy);
    resultCount = pst.executeUpdate();
    pst.close();
    return resultCount;
  }



  
  public int updateSchedule(Connection db) throws SQLException {
    int resultCount = 0;
    if (this.getId() == -1) {
      throw new SQLException("Campaign ID was not specified");
    }
    PreparedStatement pst = null;
    int i = 0;
    pst = db.prepareStatement(
        "UPDATE campaign " +
            "SET message_id = ?, " +
            "active_date = ?, active_date_timezone = ?, " +
            "send_method_id = ?, " +
            "modified = CURRENT_TIMESTAMP " +
            "WHERE campaign_id = " + id);
    //"WHERE id = " + id);
    pst.setInt(++i, messageId);
    pst.setTimestamp(++i, activeDate);
    pst.setString(++i, activeDateTimeZone);
    pst.setInt(++i, sendMethodId);
    resultCount = pst.executeUpdate();
    pst.close();
    return resultCount;
  }


  
  public int update(Connection db, boolean override) throws SQLException {
    int resultCount = 0;

    if (this.getId() == -1) {
      throw new SQLException("Campaign ID was not specified");
    }

    if (status == null) {
      if (active) {
        this.setStatusId(QUEUE);
      } else {
        this.setStatusId(IDLE);
      }
    }

    PreparedStatement pst = null;
    StringBuffer sql = new StringBuffer();
    sql.append(
        "UPDATE campaign " +
            "SET name = ?, description = ?, active_date = ?, active_date_timezone = ?, " +
            "enabled = ?, trashed_date = ?, ");
    if (cc != null && !"".equals(cc)) {
      sql.append("cc = ?, ");
    }
    if (bcc != null && !"".equals(bcc)) {
      sql.append("bcc = ?, ");
    }
    if (override && modified != null) {
      sql.append("modified = ?, ");
    } else {
      sql.append("modified = CURRENT_TIMESTAMP , ");
    }
    sql.append(
        "modifiedby = ?, " +
            "" + DatabaseUtils.addQuotes(db, "active") + " = ?, status_id = ?, status = ?, message_id = ? " +
            "WHERE campaign_id = ? ");
    int i = 0;
    pst = db.prepareStatement(sql.toString());
    pst.setString(++i, this.getName());
    pst.setString(++i, this.getDescription());
    DatabaseUtils.setTimestamp(pst, ++i, this.getActiveDate());
    pst.setString(++i, this.getActiveDateTimeZone());
    pst.setBoolean(++i, this.getEnabled());
    DatabaseUtils.setTimestamp(pst, ++i, this.getTrashedDate());
    if (cc != null && !"".equals(cc)) {
      pst.setString(++i, cc);
    }
    if (bcc != null && !"".equals(bcc)) {
      pst.setString(++i, bcc);
    }
    if (override && modified != null) {
      pst.setTimestamp(++i, modified);
    }
    pst.setInt(++i, this.getModifiedBy());
    pst.setBoolean(++i, this.getActive());
    pst.setInt(++i, this.getStatusId());
    pst.setString(++i, this.getStatus());
    pst.setInt(++i, this.getMessageId());
    pst.setInt(++i, this.getId());
    resultCount = pst.executeUpdate();
    pst.close();
    //The original survey is no longer needed
    if (statusId == FINISHED) {
//      Survey.removeLink(db, this.id);
    }
    return resultCount;
  }


  
  public boolean updateStatus(Connection db, boolean toTrash, int tmpUserId) throws SQLException {
    PreparedStatement pst = null;
    StringBuffer sql = new StringBuffer();
    sql.append(
        "UPDATE campaign " +
            "SET trashed_date = ? , " +
            "modified = CURRENT_TIMESTAMP , " +
            "modifiedby = ? " +
            "WHERE campaign_id = ? ");
    int i = 0;
    pst = db.prepareStatement(sql.toString());
    if (toTrash) {
      DatabaseUtils.setTimestamp(
          pst, ++i, new Timestamp(System.currentTimeMillis()));
    } else {
      DatabaseUtils.setTimestamp(pst, ++i, (Timestamp) null);
    }
    DatabaseUtils.setInt(pst, ++i, tmpUserId);
    pst.setInt(++i, this.getId());
    pst.executeUpdate();
    pst.close();

    //Delete the user group mappings for the campaign
    this.setBuildGroupMaps(true);
    this.buildUserGroupMaps(db);


    // remove link to instant action campaigns



    return true;
  }


  
  protected void buildRecord(ResultSet rs) throws SQLException {
    //campaign table
    this.setId(rs.getInt("campaign_id"));
    name = rs.getString("name");
    description = rs.getString("description");
    groupId = rs.getInt("list_id");
    messageId = rs.getInt("message_id");
    replyTo = rs.getString("reply_addr");
    subject = rs.getString("subject");
    message = rs.getString("message");
    statusId = rs.getInt("status_id");
    status = rs.getString("status");
    active = rs.getBoolean("active");
    activeDate = rs.getTimestamp("active_date");
    sendMethodId = rs.getInt("send_method_id");
    inactiveDate = rs.getTimestamp("inactive_date");
    approvalDate = rs.getTimestamp("approval_date");
    approvedBy = DatabaseUtils.getInt(rs, "approvedBy");
    enabled = rs.getBoolean("enabled");
    entered = rs.getTimestamp("entered");
    enteredBy = rs.getInt("enteredby");
    modified = rs.getTimestamp("modified");
    modifiedBy = rs.getInt("modifiedby");
    type = rs.getInt("type");
    activeDateTimeZone = rs.getString("active_date_timezone");
    cc = rs.getString("cc");
    bcc = rs.getString("bcc");
    trashedDate = rs.getTimestamp("trashed_date");
    //message table
    messageName = rs.getString("messageName");
    messageSubject = rs.getString("messageSubject");
    //lookup_delivery_options table
    deliveryType = rs.getInt("deliveryType");
    deliveryName = rs.getString("deliveryTypeName");
  }


  
  public int lockProcess(Connection db) throws SQLException {
    PreparedStatement pst = db.prepareStatement(
        "UPDATE campaign " +
            "SET status_id = ?, " +
            "modified = CURRENT_TIMESTAMP " +
            "WHERE campaign_id = ? " +
            "AND status_id = ? ");
    pst.setInt(1, statusId);
    pst.setInt(2, id);
    pst.setInt(3, Campaign.QUEUE);
    int count = pst.executeUpdate();
    pst.close();
    return count;
  }


  
  public final static int queryEnteredBy(Connection db, int campaignId) throws SQLException {
    int enteredBy = -1;
    PreparedStatement pst = db.prepareStatement(
        "SELECT enteredby " +
            "FROM campaign " +
            "WHERE campaign_id = ? ");
    pst.setInt(1, campaignId);
    ResultSet rs = pst.executeQuery();
    if (rs.next()) {
      enteredBy = rs.getInt("enteredby");
    }
    rs.close();
    pst.close();
    return enteredBy;
  }


  
  public static ArrayList getUserIdParams() {
    ArrayList thisList = new ArrayList();
    thisList.add("enteredBy");
    thisList.add("modifiedBy");
    thisList.add("owner");
    return thisList;
  }




  
  public static boolean authenticateForBroadcast(Connection db, int tmpUserId, String password) throws SQLException {
    String pw = "";
    String encryptedPassword = PasswordHash.encrypt(password);
    PreparedStatement pst = db.prepareStatement(
        "SELECT a.password " +
            "FROM  ts_account a " +
            "WHERE user_id = ? " +
            "AND a.enabled = ? ");
    pst.setInt(1, tmpUserId);
    pst.setBoolean(2, true);
    ResultSet rs = pst.executeQuery();
    if (rs.next()) {
      pw = rs.getString("password");
    }
    rs.close();
    pst.close();
    if (pw == null || pw.trim().equals("") || !pw.equals(encryptedPassword)) {
      return false;
    }
    return true;
  }


  
  public boolean restartCampaign(Connection db) throws SQLException {
    if (this.getId() == -1) {
      throw new SQLException("Campaign ID required to restart the campaign");
    }
    String currentTimestamp = DatabaseUtils.getCurrentTimestamp(db);
    PreparedStatement pst = db.prepareStatement(
        "UPDATE campaign SET " +
            "status_id = ?, " +
            "status = ?, " +
            "active_date = " + currentTimestamp + ", " +
            "modified = CURRENT_TIMESTAMP " +
            "WHERE campaign_id = ? ");
    pst.setInt(1, Campaign.QUEUE);
    pst.setString(2, Campaign.QUEUE_TEXT);
    pst.setInt(3, this.getId());
    pst.executeUpdate();
    pst.close();
    return true;
  }


  
  public void buildMessageAttachments(Connection db) throws SQLException {  
	  messageAttachments= new MessageAttachmentList(db,"campaign",id);
  }

}
